package com.tourism.controller;

/**
 * @Description
 * @Author z
 * @Date 2021-04-04 16:41
 */

import com.tourism.util.common.Response;
import org.apache.tomcat.util.http.fileupload.IOUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.UUID;

/**
 * @Description
 * @Author sgl
 * @Date 2018-05-15 14:04
 */
@Controller
@RequestMapping(("/file"))
public class UploadController {
    private static final Logger LOGGER = LoggerFactory.getLogger(UploadController.class);

    @Value("${upload.path}")
    private String filePath;

    @PostMapping("/upload")
    @ResponseBody
    public Response upload(@RequestParam("file") MultipartFile file) {

        if (file.isEmpty()) {
            return Response.error("文件为空");
        }


        String fileSuffix = file.getOriginalFilename().split("\\.")[1];
        String fileName = UUID.randomUUID().toString() + "." + fileSuffix;
        File dest = new File(filePath + fileName);
        try {
            file.transferTo(dest);
            return Response.success(fileName, "文件上传成功！");
        } catch (IOException e) {
            LOGGER.error(e.toString(), e);
        }
        return Response.error("文件上传失败！");
    }

    @GetMapping("/getFile")
    public void getFile(String fileName, HttpServletResponse response) {
        try {
            IOUtils.copy(new FileInputStream(filePath + fileName), response.getOutputStream());
        } catch (IOException e) {
            LOGGER.error(e.toString(), e);
        }
    }


}
